//
//  ViewController.m
//  bgCar
//
//  Created by cckv on 2017/9/22.
//  Copyright © 2017年 kv. All rights reserved.
//

#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "tipView2.h"
@interface ViewController (){
    CGFloat _timerInterval;
    CGFloat _speedY;
    CGRect  _originFrame;

    CGFloat _CarX1;
    CGFloat _CarX2;
    CGFloat _CarX3;
    CGFloat _CarX4;
    CGFloat _carLengthTime;
    CGFloat _speedCarY;
    NSInteger _showOtherCarFlag;
    
}

@property (nonatomic,weak)   UIImageView * roadImgView1;
@property (nonatomic,weak)   UIImageView * roadImgView2;

@property (nonatomic,weak)   UIImageView * myCar;

@property (nonatomic,strong) NSMutableArray * otherCarArr;

@property (nonatomic,strong) CADisplayLink * runTimer;

@property (nonatomic,weak)   UILabel * numLabel;

@property (nonatomic,strong) UIButton * restartBtn;
@property (nonatomic,strong) UIButton * stopBtn;


@property (nonatomic,weak) UILabel *timeL;

@property (nonatomic,weak)  UIButton * leftBtn;
@property (nonatomic,weak) UIButton * rightBtn;

@property (strong, nonatomic) ZJAnimationPopView *popView;
@property (strong, nonatomic) tipView2 *tipV;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 初始化基本数据
    [self initSetUp];
    
    // 设置控件
    [self setupSubViews];
    
}

// 初始化基本数据
-(void)initSetUp
{
    _speedY = 3;
    
    CGFloat carW = kScreenWidth/6;
    
    _CarX1 = 1 * carW;
    _CarX2 = 2 * carW;
    _CarX3 = 3 * carW;
    _CarX4 = 4 * carW;
    
    _speedCarY = 6;
}

// 设置控件
- (void)setupSubViews
{
    
    CGFloat roadH =  kScreenWidth * 4100/1043;
    CGFloat roadY = kScreenHeight-roadH;
    _originFrame = CGRectMake(0,-roadH+10, kScreenWidth,roadH);
    
    //road1
    UIImageView * roadImgView = [[UIImageView alloc]init];
    roadImgView.frame = CGRectMake(0, roadY, kScreenWidth, roadH);
    self.roadImgView1 = roadImgView;
    roadImgView.image = [UIImage imageNamed:@"赛车UI.jpg"];
    [self.view addSubview:roadImgView];
    
    //road2
    UIImageView * roadImgView2 = [[UIImageView alloc]init];
    roadImgView2.frame = CGRectMake(0, roadY-roadH, kScreenWidth, roadH);
    roadImgView2.image = self.roadImgView1.image;
    self.roadImgView2 = roadImgView2;
    [self.view addSubview:roadImgView2];
    
    //myCar;
    CGFloat carW = kScreenWidth/6 - 5;
    CGFloat carH = carW * 1.5;
    CGFloat carY = kScreenHeight - carH - 50;
    UIImageView * myCar = [[UIImageView alloc]init];
    myCar.frame = CGRectMake(_CarX2, carY, carW, carH);
    self.myCar = myCar;
    myCar.image = [UIImage imageNamed:self.myCarName];
    [self.view addSubview:myCar];
    _carLengthTime = carH/_speedCarY*2.5;
    
    //分数显示：
    CGFloat w = 100;
    UILabel * scoreLabel = [[UILabel alloc]initWithFrame:CGRectMake(kScreenWidth/2-w+5,24,w,40)];
    scoreLabel.textAlignment = 2;
    [self.view addSubview:scoreLabel];
    scoreLabel.font  = [UIFont boldSystemFontOfSize:25];
//    scoreLabel.text = @"GET :";
    scoreLabel.text = NSLocalizedString(@"GET :", nil);
    scoreLabel.textColor  = [UIColor redColor];
    
    UILabel * numLabel = [[UILabel alloc]initWithFrame:CGRectMake(kScreenWidth/2+5, 24, w, 40)];
    self.numLabel = numLabel;
    numLabel.textColor = [UIColor redColor];
    numLabel.textAlignment = 0;
    [self.view addSubview:numLabel];
    numLabel.font  = [UIFont boldSystemFontOfSize:25];

    //restart
    CGFloat btnW = 35;
    UIButton * stopBtn = [[UIButton alloc]initWithFrame:CGRectMake(kScreenWidth-btnW-15, 24, btnW, btnW)];
    self.stopBtn = stopBtn;
    
    NSArray *appLanguages = [[NSUserDefaults standardUserDefaults] objectForKey:@"AppleLanguages"];
    NSString *languageName = [appLanguages objectAtIndex:0];
    if ([languageName isEqualToString:@"en-US"]) {
        [stopBtn setImage:[UIImage imageNamed:@"暂停.png"] forState:UIControlStateNormal];
    }else{
        [stopBtn setImage:[UIImage imageNamed:@"赛车UI_03"] forState:UIControlStateNormal];
    }
    [stopBtn setImage:[UIImage imageNamed:@"contius"] forState:UIControlStateSelected];
    [self.view addSubview:stopBtn];
    [stopBtn addTarget:self action:@selector(stopAction) forControlEvents:UIControlEventTouchUpInside];
    
    CGFloat W = 35;
    UIButton * restartBtn = [[UIButton alloc]initWithFrame:CGRectMake(15, 24, W, W)];
    self.restartBtn = restartBtn;
    [restartBtn setImage:[UIImage imageNamed:@"restart"] forState:UIControlStateNormal];
    [self.view addSubview:restartBtn];
    restartBtn.hidden = YES;
    [restartBtn addTarget:self action:@selector(restartAction) forControlEvents:UIControlEventTouchUpInside];
    
    // 障碍车辆初始化
    [self otherCarArr];
    
    //左右按钮：
    CGFloat controlBtnW = 70;
    CGFloat leftSpace = 50;
    UIButton * leftBtn = [[UIButton alloc]initWithFrame:CGRectMake(leftSpace,kScreenHeight-controlBtnW-20, controlBtnW, controlBtnW)];
    self.leftBtn = leftBtn;
    [leftBtn setImage:[UIImage imageNamed:@"left"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(leftRightBtn:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:leftBtn];
    leftBtn.tag = 1;
    
    UIButton * rightBtn = [[UIButton alloc]initWithFrame:CGRectMake(kScreenWidth-controlBtnW-leftSpace, kScreenHeight-controlBtnW-20, controlBtnW, controlBtnW)];
    self.rightBtn = rightBtn;
    [rightBtn setImage:[UIImage imageNamed:@"right"] forState:UIControlStateNormal];
    [self.view addSubview:rightBtn];
    [rightBtn addTarget:self action:@selector(leftRightBtn:) forControlEvents:UIControlEventTouchUpInside];
    rightBtn.tag = 2;
    
    UILabel *timeL = [UILabel new];
    timeL.center = self.view.center;
    timeL.size = CGSizeMake(60, 60);
    timeL.textColor = [UIColor whiteColor];
    timeL.font = [UIFont systemFontOfSize:50];
    [self.view addSubview:timeL];
    self.timeL = timeL;
    timeL.text = @"3";
    if ([[[NSUserDefaults standardUserDefaults]objectForKey:@"playMusic"] boolValue]) {
        
        [[KVPlayer shareTool]palyWithName:@"6503" andType:@"wav"];
    }
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        timeL.text = @"2";
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            timeL.text = @"1";
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                if ([[[NSUserDefaults standardUserDefaults]objectForKey:@"playMusic"] boolValue]) {
                    
                    [[KVPlayer shareTool]palyWithName:@"5228" andType:@"wav"];
                }
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    if ([[[NSUserDefaults standardUserDefaults]objectForKey:@"playMusic"] boolValue]) {
                        
                        [[KVPlayer shareTool]palyWithName:@"汽车引擎" andType:@"wav"];
                    }
                });
                self.timeL.hidden = YES;
                //计时器：
                CADisplayLink * runTimer = [CADisplayLink displayLinkWithTarget:self selector:@selector(runTimerAction)];
                [runTimer addToRunLoop:[NSRunLoop currentRunLoop]
                               forMode:NSDefaultRunLoopMode];
                self.runTimer  = runTimer;
            });
        });
    });
    
}

/**
 * 赛车左右移动:按钮
 */
- (void)leftRightBtn:(UIButton *)btn
{
    CGFloat carW = kScreenWidth/6;
    if (btn.tag == 1) {
        [UIView animateWithDuration:0.15 animations:^{
//            self.myCar.x = _leftCarX;
            
            if (self.myCar.x > _CarX1) {
                
                self.myCar.x -= carW;
                
            }else{
                
            }
        }];
    }
    else{
        [UIView animateWithDuration:0.15 animations:^{
//            self.myCar.x = _RightCarX;
            if (self.myCar.x>=_CarX4) {
                
            }else{
                
                self.myCar.x += carW;
            }
        }];
    }
}



/**
 * 定时器方法：
 */
- (void)runTimerAction{
    
    [self transferBgView];
    
    [self showOtherCar];
    
    [self transferOtherCar];
}
- (void)stopAction
{
    self.stopBtn.selected = !self.stopBtn.selected;
    
    if (self.stopBtn.tag == 100) {
        [self.runTimer setPaused:YES];
        self.restartBtn.hidden = NO;
        self.leftBtn.enabled = NO;
        self.rightBtn.enabled = NO;
        [self dismissViewControllerAnimated:YES completion:nil];
        return;
    }
    
    if (self.stopBtn.selected) {
        [self.runTimer setPaused:YES];
        self.restartBtn.hidden = NO;
        self.leftBtn.enabled = NO;
        self.rightBtn.enabled = NO;
        [[KVPlayer shareTool]stop];
    }else{
        [self.runTimer setPaused:NO];
        self.restartBtn.hidden = YES;
        self.leftBtn.enabled = YES;
        self.rightBtn.enabled = YES;
        if ([[[NSUserDefaults standardUserDefaults]objectForKey:@"playMusic"] boolValue]) {
            
            [[KVPlayer shareTool]palyWithName:@"汽车引擎" andType:@"wav"];
        }
    }
}
/**
 * 重来游戏：
 */
- (void)restartAction
{
    if ([[[NSUserDefaults standardUserDefaults]objectForKey:@"playMusic"] boolValue]) {
        
        [[KVPlayer shareTool]palyWithName:@"汽车引擎" andType:@"wav"];
    }
    
    self.stopBtn.hidden = NO;
    self.stopBtn.selected = NO;
    self.restartBtn.hidden = YES;
    self.leftBtn.enabled = YES;
    self.rightBtn.enabled = YES;
//    self.gesView.userInteractionEnabled = YES;
    
    for (otherCarView * otherCarImgView in self.otherCarArr) {
        if (otherCarImgView.isOnScreen) {
            otherCarImgView.hidden = YES;
            otherCarImgView.isOnScreen = NO;
        }
    }
    
    _showOtherCarFlag = 0;//重新开始计。
    
    self.timeL.hidden = NO;
    self.timeL.text = @"3";
    if ([[[NSUserDefaults standardUserDefaults]objectForKey:@"playMusic"] boolValue]) {
        
        [[KVPlayer shareTool]palyWithName:@"6503" andType:@"wav"];
    }
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.timeL.text = @"2";
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            self.timeL.text = @"1";
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                if ([[[NSUserDefaults standardUserDefaults]objectForKey:@"playMusic"] boolValue]) {
                    
                    [[KVPlayer shareTool]palyWithName:@"5228" andType:@"wav"];
                }
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    if ([[[NSUserDefaults standardUserDefaults]objectForKey:@"playMusic"] boolValue]) {
                        
                        [[KVPlayer shareTool]palyWithName:@"汽车引擎" andType:@"wav"];
                    }
                });
                self.timeL.hidden = YES;
                //计时器：
                self.runTimer =[CADisplayLink displayLinkWithTarget:self selector:@selector(runTimerAction)];
                [self.runTimer addToRunLoop:[NSRunLoop currentRunLoop]
                                    forMode:NSDefaultRunLoopMode];
            });
        });
    });
    
    
}


/**
 * 背景移动
 */
- (void)transferBgView
{
    
    static int i;
    if (i == 0) {//图片1 - 移动
        [UIView animateWithDuration:_timerInterval animations:^{
            if (self.roadImgView1.y>-_speedY) {
                self.roadImgView2.hidden = NO;
                self.roadImgView2.frame = _originFrame;
                i = 1;
            }
            self.roadImgView1.y += _speedY;
            
            //调整图片2的移动
            if (self.roadImgView2.y<kScreenHeight) {
                self.roadImgView2.y+= _speedY;
            }
            if (self.roadImgView2.y>kScreenHeight) {
                self.roadImgView2.hidden = YES;
            }
        }];
    }else{//图片2 - 移动
        [UIView animateWithDuration:_timerInterval animations:^{
            if (self.roadImgView2.y>_speedY) {
                self.roadImgView1.hidden = NO;
                self.roadImgView1.frame = _originFrame;
                i = 0;
            }
            self.roadImgView2.y += _speedY;
            
            //调整图片1的移动。
            if (self.roadImgView1.y<kScreenHeight) {
                self.roadImgView1.y+= _speedY;
            }
            if (self.roadImgView1.y>kScreenHeight) {
                self.roadImgView1.hidden = YES;
            }
        }];
    }
}


/**
 * 出现对方汽车：
 */
- (void)showOtherCar
{
    //对面出现车辆：
    if ((_showOtherCarFlag % (int)_carLengthTime) == 0) {
        for (otherCarView * carImgView in self.otherCarArr) {
            if (!carImgView.isOnScreen) {
                carImgView.hidden = NO;
                carImgView.isOnScreen = YES;
//                CGFloat x = arc4random()%2?_leftCarX:_RightCarX;
                CGFloat x = 0;
                int i = arc4random()%4;
                switch (i) {
                    case 0:
                        x = _CarX1;
                        break;
                    case 1:
                        x = _CarX2;
                        break;
                    case 2:
                        x = _CarX3;
                        break;
                    case 3:
                        x = _CarX4;
                        break;
                        
                    default:
                        break;
                }
                carImgView.x = x;
                carImgView.y = -200;
                break;
            }
        }
    }
    _showOtherCarFlag++;
    
    //更新分数：
    self.numLabel.text = [NSString stringWithFormat:@"%ld 🏁",_showOtherCarFlag/50];
    
}


/**
 * 移动汽车：
 **/
- (void)transferOtherCar
{
    for (UIView * subView in self.view.subviews) {
        if ([subView isKindOfClass:[otherCarView class]]) {
            otherCarView * carImgView = (otherCarView *)subView;
            if (carImgView.isOnScreen) {
                
                if (carImgView.y<kScreenHeight) {
                    carImgView.y += _speedCarY;
                }else{
                    //移除汽车：
                    carImgView.isOnScreen = NO;
                    carImgView.hidden = YES;
                }
                //检查车子碰撞情况：
                CGRect judgeFrame = CGRectMake(_myCar.x, _myCar.y+30, _myCar.width, _myCar.height-60);
                if (CGRectIntersectsRect(carImgView.frame,judgeFrame)) {
                    [self.runTimer invalidate];
                    
                    [self bang];
                    [[KVPlayer shareTool]stop];
                    
                    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
                                    
                    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
                    
                    NSDate *datenow = [NSDate date];
                    
                    NSString *currentTimeString = [formatter stringFromDate:datenow];
                    
                    dataModel *model = [dataModel new];
                    model.score = self.numLabel.text;
                    model.timeStr = currentTimeString;
                    [model save];
                    
                    NSString *str = [NSString stringWithFormat:@"%@ %@. %@",NSLocalizedString(@"Congratulations.You've got", nil) ,self.numLabel.text,NSLocalizedString(@"Do you want to try again?", nil)];
                    
                    dispatch_async(dispatch_get_main_queue(), ^{
                        tipView2 *v= [tipView2 vieFromXib];
                        v.center = self.view.center;
                        v.size = CGSizeMake(kScreenWidth-30, 160);
                        self.tipV = v;
                        
                        v.tip.text = str;
                        [v.btn1 setTitle:NSLocalizedString(@"取消", nil) forState:UIControlStateNormal];
                        [v.btn2 setTitle:NSLocalizedString(@"确定", nil) forState:UIControlStateNormal];
                        [v.btn1 addTarget:self action:@selector(quxiao) forControlEvents:UIControlEventTouchUpInside];
                        [v.btn2 addTarget:self action:@selector(queding) forControlEvents:UIControlEventTouchUpInside];
                        
                        ZJAnimationPopView *popView = [[ZJAnimationPopView alloc]initWithCustomView:v popStyle:ZJAnimationPopStyleShakeFromTop dismissStyle:ZJAnimationDismissStyleDropToBottom];
                        [popView pop];
                        self.popView = popView;
                    });

                    
                    break;
                }
                
            }
        }
    }
}
- (void)quxiao
{
    self.restartBtn.hidden = NO;
    //                        self.gesView.userInteractionEnabled = NO;
    self.leftBtn.enabled = NO;
    self.rightBtn.enabled = NO;
    //                        self.stopBtn.hidden = YES;
    //                        [self.stopBtn setTitle:NSLocalizedString(@"back", nil) forState:UIControlStateNormal];
    [self.stopBtn setImage:[[UIImage imageNamed:@"返回return"]imageByTintColor:[UIColor whiteColor]] forState:UIControlStateNormal];
    self.stopBtn.tag = 100;
    [self.popView dismiss];
}
- (void)queding
{
    [self restartAction];
    [self.popView dismiss];
}
#pragma mark - 爆炸声音
- (void)bang
{
    NSString *audioFile=[[NSBundle mainBundle] pathForResource:@"爆炸.wav" ofType:nil];
    NSURL *fileUrl=[NSURL fileURLWithPath:audioFile];
    //1.获得系统声音ID
    SystemSoundID soundID=0;
    /**
     * inFileUrl:音频文件url
     * outSystemSoundID:声音id（此函数会将音效文件加入到系统音频服务中并返回一个长整形ID）
     */
    AudioServicesCreateSystemSoundID((__bridge CFURLRef)(fileUrl), &soundID);
    //如果需要在播放完之后执行某些操作，可以调用如下方法注册一个播放完成回调函数
    //2.播放音频
    AudioServicesPlaySystemSound(soundID);//播放音效
    AudioServicesPlayAlertSound(soundID);//播放音效并震动
    
}

/** 障碍车 */
-(NSMutableArray *)otherCarArr
{
    if (!_otherCarArr) {
        _otherCarArr = @[].mutableCopy;
        for (int i = 1; i<10; i++) {
            otherCarView * carImg = [[otherCarView alloc]init];
            carImg.isOnScreen = NO;
            carImg.hidden = YES;
            carImg.image = [UIImage imageNamed:[NSString stringWithFormat:@"car%d",i%6+1]];
            [self.view addSubview:carImg];
            carImg.size = self.myCar.size;
            [_otherCarArr addObject:carImg];
        }
    }
    return _otherCarArr;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
